/**
 * 将 markdownIt 的 heading 列表转换为树形结构
 * @param list
 */
export const createOutline = (list: any) => {
    const outlineList = [];

    const findParent = (node, level) => {
        if (node.level + 1 === level) {
            return node;
        }
        for (let child of node.children || []) {
            const result = findParent(child, level);
            if (result) return result;
        }
        return null;
    };

    list.forEach(item => {
        if (item.level === 1) {
            // 当前项是顶级节点
            outlineList.push({
                level: item.level,
                content: item.content,
                children: []
            });
        } else {
            // 寻找父节点
            const parentNode = outlineList.reduce((acc, curr) => {
                const parent = findParent(curr, item.level);
                return parent || acc;
            }, null);

            if (parentNode) {
                // 找到了父节点，将当前项作为子节点添加
                parentNode.children.push({
                    level: item.level,
                    content: item.content,
                    children: []
                });
            } else {
                // 没有找到父节点，可能是数据错误或逻辑错误
                console.error(`Could not find parent for item with level ${item.level}:`, item);
            }
        }
    });

    return outlineList;
}

/**
 * 将文本进行编码
 */
export const encodeText = (text: string) => {
    return btoa(unescape(encodeURIComponent(text)));
}

/*
* 解码
* */
export const decodeText = (text: string) => {
    return decodeURIComponent(escape(atob(text)));
}


/*
* 获取图片路径前缀
* */
export const ImagePrefix = '/api-file/'

export const getFullUrl = (path: string) => {
    return ImagePrefix + path
}
